# -*- coding: utf-8 -*-
from typing import Optional

from fastapi import APIRouter, Depends
from starlette.background import BackgroundTasks

chapter06 = APIRouter()

""" run.py 中 Middleware 中间件"""
# 带yield的依赖的退出部分代码和后台任务，会在中间件之后运行


""" run.py 中 CORS （cross-origin resource Sharing）跨域资源共享 """

"""Background Tasks 后台任务"""


async def bg_task(framework: str):
    with open("README.md", mode="a") as f:
        f.write(f"## {framework} - 后台任务")

@chapter06.post("/background_tasks")
async def run_bg_task(framework: str, background_task: BackgroundTasks):
    """

    :param framework: 被调用的后台函数参数
    :param background_task:
    :return:
    """
    background_task.add_task(bg_task, framework)
    return {"message": "任务已在后台运行"}


# 依赖后台任务
def continue_write_readme(background_task: BackgroundTasks, q: Optional[str] = None):
    if q:
        background_task.add_task(bg_task, "\r\n> FastAPI Learn")
    return q


@chapter06.post("/dependency/background_tasks")
async def run_dependency_bg_task(q: str = Depends(continue_write_readme)):
    if q:
        return {"message": "任务已在后台运行"}


